package com.mrobuy.jdvc.controller;

import com.gavel.utils.StringUtils;
import com.mrobuy.jd.JdClientFactory;
import com.mrobuy.jd.brand.VCBrandLoader;
import com.mrobuy.jdvc.Result;
import com.mrobuy.jdvc.dao.*;
import com.mrobuy.jdvc.entity.*;
import com.mrobuy.jdvc.service.ItemPropService;
import com.mrobuy.jdvc.service.ShelvesService;
import com.mrobuy.util.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Controller
public class CateBrandController {

	@Autowired
	private VCCateBrandDao vcCateBrandDao;

	@Autowired
	private VCCategotyDao vcCategotyDao;

	@Autowired
	private VCBrandDao vcBrandDao;


	@RequestMapping("/catebrand")
	public String catebrand(Model model) {

		model.addAttribute("categories", vcCategotyDao.list());
		model.addAttribute("brands", vcBrandDao.list());

		return "catebrand";
	}


	@RequestMapping("/catebrand/query")
	@ResponseBody
	public Object query(HttpServletRequest request, VCCateBrand condition) {

		int start = ServletRequestUtils.getIntParameter(request, "start", 1);
		int length = ServletRequestUtils.getIntParameter(request, "length", 100);

		int draw = ServletRequestUtils.getIntParameter(request, "draw", 1);


		Pagination pagination = vcCateBrandDao.load(start, length, condition);

		//int offset = page*pagesize - pagesize;
		pagination.setDraw(draw);

		return pagination;
	}

	@RequestMapping("/catebrand/add")
	@ResponseBody
	public Result add(HttpServletRequest request, VCCateBrand record) {

		Result result = null;
		try {

			VCCategory vcCate = vcCategotyDao.load(String.valueOf(record.getCateid()));

			VCBrand vcBrand = vcBrandDao.load(String.valueOf(record.getBrandid()));

			if ( vcCate!=null ) {
				record.setCatename(vcCate.getName());
			}

			if ( vcBrand!=null ) {
				record.setName(vcBrand.getName());
			}


			result = vcCateBrandDao.insert(record);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false);
			result.setMsg(e.getMessage());
		}

		return result;
	}

}
